const Ajv = require('ajv');
const localize = require('ajv-i18n');

/**
 * 数据验证
 */
module.exports = (data, schema, alloweThrow = true, allErrors) => {
    const ajv = Ajv({ allErrors });
    const validate = ajv.compile(schema);
    const valid = validate(data);

    if (!valid) {
        localize.zh(validate.errors);

        const error = ajv.errorsText(validate.errors, { separator: '\n' });

        if (alloweThrow) {
            throw error;
        }

        return error;
    }
}